let currentMonth = new Date();
let selectedDate = null;
let calendarSummary = [];

document.addEventListener('DOMContentLoaded', () => {
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    if (!Auth.checkRole(UserRole.SITE_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => Auth.logout(), 2000);
        return;
    }

    init();
});

async function init() {
    displayUserInfo();
    
    // 检查并显示低库存预警
    await checkAndShowLowStockAlert();
    
    renderWeekdays();
    await loadCalendarSummary();
}

function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (!userInfo) return;
        const userName = userInfo.account || '管理员';
        document.getElementById('userName').textContent = userName;
    document.getElementById('userAvatar').textContent = userName.charAt(0).toUpperCase();
}

function renderWeekdays() {
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    const container = document.getElementById('calendarWeekdays');
    if (!container) return;
    container.innerHTML = '';
    weekdays.forEach(label => {
        const div = document.createElement('div');
        div.className = 'calendar-weekday';
        div.textContent = label;
        container.appendChild(div);
    });
}

function formatMonth(date) {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
}

function changeMonth(offset) {
    currentMonth.setMonth(currentMonth.getMonth() + offset);
    loadCalendarSummary();
}

async function loadCalendarSummary() {
    const monthStr = formatMonth(currentMonth);
    document.getElementById('calendarMonthLabel').textContent =
        `${currentMonth.getFullYear()}年${currentMonth.getMonth() + 1}月`;

    try {
        const data = await HttpClient.get(`/admin/appointment/calendar?month=${monthStr}`);
        calendarSummary = Array.isArray(data) ? data : [];
        renderCalendarGrid();
        autoSelectDate();
    } catch (error) {
        console.error('加载日历失败:', error);
        UI.showMessage('加载预约日历失败', 'danger');
    }
}

function renderCalendarGrid() {
    const grid = document.getElementById('calendarGrid');
    if (!grid) return;
    grid.innerHTML = '';

    const summaryMap = {};
    calendarSummary.forEach(item => summaryMap[item.date] = item);

    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    const firstDay = new Date(year, month, 1);
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const startWeekday = firstDay.getDay();

    for (let i = 0; i < startWeekday; i++) {
        const empty = document.createElement('div');
        empty.className = 'calendar-day calendar-empty';
        grid.appendChild(empty);
    }

    for (let day = 1; day <= daysInMonth; day++) {
        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        const summary = summaryMap[dateStr];

        const cell = document.createElement('div');
        cell.className = 'calendar-day';
        cell.dataset.date = dateStr;

        if (summary && summary.totalCount > 0) {
            cell.classList.add('has-appointments');
        }
        if (selectedDate === dateStr) {
            cell.classList.add('selected');
        }

        const dot = summary && summary.totalCount ? '<span class="calendar-day-dot"></span>' : '';
        cell.innerHTML = `
            <div class="calendar-day-number">${day}</div>
            <div class="calendar-day-count">${summary && summary.totalCount ? summary.totalCount : ''}</div>
            ${dot}
        `;

        cell.addEventListener('click', () => handleDaySelection(dateStr, summary));
        grid.appendChild(cell);
    }

    const totalCells = grid.children.length;
    const rows = Math.ceil(totalCells / 7);
    const needed = rows * 7 - totalCells;
    for (let i = 0; i < needed; i++) {
        const empty = document.createElement('div');
        empty.className = 'calendar-day calendar-empty';
        grid.appendChild(empty);
    }
}

function autoSelectDate() {
    if (calendarSummary.length === 0) {
        selectedDate = null;
        document.getElementById('selectedDateLabel').textContent = '本月暂无预约';
        document.getElementById('selectedDateSummary').textContent = '请选择其他月份查看';
        renderAppointmentTable([]);
        updateStatistics([]);
        return;
    }
    const first = calendarSummary
        .sort((a, b) => new Date(a.date) - new Date(b.date))[0];
    handleDaySelection(first.date, first);
}

function handleDaySelection(dateStr, summary) {
    selectedDate = dateStr;
    document.querySelectorAll('.calendar-day').forEach(day => day.classList.remove('selected'));
    const active = document.querySelector(`.calendar-day[data-date="${dateStr}"]`);
    if (active) active.classList.add('selected');

    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    document.getElementById('selectedDateLabel').textContent =
        new Date(dateStr.replace(/-/g, '/')).toLocaleDateString('zh-CN', options);
    const count = summary && summary.totalCount ? summary.totalCount : 0;
    document.getElementById('selectedDateSummary').textContent =
        count > 0 ? `共有 ${count} 条预约记录` : '该日期暂无预约';

    loadAppointmentsByDate(dateStr);
}

function refreshSelectedDate() {
    if (!selectedDate) {
        UI.showMessage('请先选择日期', 'info');
        return;
    }
    const summary = calendarSummary.find(item => item.date === selectedDate);
    handleDaySelection(selectedDate, summary);
}

async function loadAppointmentsByDate(dateStr) {
    const tbody = document.getElementById('appointmentTableBody');
    if (!tbody) return;
    tbody.innerHTML = `
        <tr>
            <td colspan="7" style="text-align:center;padding:40px;color:#999;">
                <i class="fas fa-spinner fa-spin"></i> 加载中...
            </td>
        </tr>
    `;

    try {
        const list = await HttpClient.get(`/admin/appointment/by-date?date=${dateStr}`);
        const appointments = Array.isArray(list) ? list : [];
        updateStatistics(appointments);
        renderAppointmentTable(appointments);
    } catch (error) {
        console.error('加载预约详情失败:', error);
        UI.showMessage('加载预约详情失败', 'danger');
        tbody.innerHTML = `
            <tr><td colspan="7" style="text-align:center;padding:40px;color:#ff6b6b;">加载失败</td></tr>
        `;
    }
}

function updateStatistics(appointments) {
    const total = appointments.length;
    const pending = appointments.filter(a => a.appointmentStatus === 1).length;
    const completed = appointments.filter(a => a.appointmentStatus === 2).length;
    const cancelled = appointments.filter(a => a.appointmentStatus === -1).length;

    document.getElementById('totalAppointments').textContent = total;
    document.getElementById('pendingAppointments').textContent = pending;
    document.getElementById('completedAppointments').textContent = completed;
    document.getElementById('cancelledAppointments').textContent = cancelled;
}

function renderAppointmentTable(appointments) {
    const tbody = document.getElementById('appointmentTableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    if (!appointments || appointments.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align:center;padding:40px;color:#999;">暂无预约记录</td>
            </tr>
        `;
        return;
    }
    
    appointments.forEach(appointment => {
        const canComplete = appointment.appointmentStatus === 1;
        const actionButton = canComplete
            ? `<button class="btn btn-success btn-sm" onclick="handleCompleteAppointment(${appointment.id})">
                <i class="fas fa-check"></i> 完成接种
               </button>`
            : `<span class="badge ${Format.appointmentStatusBadge(appointment.appointmentStatus)}">
                ${Format.appointmentStatus(appointment.appointmentStatus)}
            </span>`;
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${appointment.id}</td>
            <td>${appointment.personName || '-'}</td>
            <td>${appointment.vaccineName || '-'}</td>
            <td><span class="badge badge-info">${Format.vaccineType(appointment.vaccineType)}</span></td>
            <td>${Format.date(appointment.appointmentTime)}</td>
            <td>
                <span class="badge ${Format.appointmentStatusBadge(appointment.appointmentStatus)}">
                    ${Format.appointmentStatus(appointment.appointmentStatus)}
                </span>
            </td>
            <td>${actionButton}</td>
        `;
        tbody.appendChild(row);
    });
}

async function handleCompleteAppointment(appointmentId) {
    UI.confirm('确定将此预约标记为已完成吗？', async () => {
        try {
            await HttpClient.put(`/admin/appointment/${appointmentId}/status`, { status: 2 });
            UI.showMessage('更新状态成功', 'success');
            if (selectedDate) {
                await loadAppointmentsByDate(selectedDate);
                await loadCalendarSummary();
            }
        } catch (error) {
            console.error('更新状态失败:', error);
            UI.showMessage(error.message || '更新状态失败', 'danger');
        }
    });
}

function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => Auth.logout());
}


